package com.atguigu.srb;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 * @author gcq
 * @Create 2021-04-30
 */
public class JwtTests {
    private static long tokenExpiration = 1000 * 60 * 60 * 24;
    private static String tokenSignKey = "atguigu123";


    public static void main(String[] args) {
//        jwtTest();
        testGetUserInfo();
    }

    /**
     * jwt生成
     */
    private static void jwtTest() {
        JwtBuilder jwtBuilder = Jwts.builder();
        // 头、载荷、签名哈希
        String jwtToken = jwtBuilder
                // 头
                .setHeaderParam("alg", "HS256") // 签名使用的算法
                .setHeaderParam("typ", "JWT") // typ表示令牌的类型

                // 载荷：自定义信息 JWT的主体内容部分
                .claim("nickname", "") // 相关用户的信息
                .claim("avatar", "1.jpg")
                .claim("role", "admin")

                // 载荷：默认信息
                .setSubject("srb-user") // 令牌主题
                .setIssuer("atguigu") // jwt签发者
                .setAudience("atguigu") // 接受jwt一方
                .setIssuedAt(new Date()) // jwt签发时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) // jwt过期时间 这里设置为一天
                .setNotBefore(new Date(System.currentTimeMillis() + 1000 * 20)) // 什么时间之前该jwt不可用
                .setId(UUID.randomUUID().toString()) // jwt唯一身份标识

                .signWith(SignatureAlgorithm.HS256, tokenSignKey) //
                // 组装jwt字符串
        .compact();
        System.out.println("jwtToken" + jwtToken);
    }

    public static void testGetUserInfo() {
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuaWNrbmFtZSI6IiIsImF2YXRhciI6IjEuanBnIiwicm9sZSI6ImFkbWluIiwic3ViIjoic3JiLXVzZXIiLCJpc3MiOiJhdGd1aWd1IiwiYXVkIjoiYXRndWlndSIsImlhdCI6MTYxOTgzMDc3NCwiZXhwIjoxNjE5OTE3MTc0LCJuYmYiOjE2MTk4MzA3OTQsImp0aSI6IjFlNWYyN2U1LWVhMjktNDAyZC05YzMzLTYzZTU1N2JmODA1MSJ9.0nU2Ya56L7k9Q3rcyQw9chpoBPJhtMyUA68KbcL2OaU";
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(tokenSignKey).parseClaimsJws(token);

        Claims body = claimsJws.getBody();
        String subject = body.getSubject();
        String issuer = body.getIssuer();
        String audience = body.getAudience();
        Date issuedAt = body.getIssuedAt();
        Date expiration = body.getExpiration();
        Date notBefore = body.getNotBefore();
        String id = body.getId();

        System.out.println(subject);
        System.out.println(issuer);
        System.out.println(audience);
        System.out.println(expiration);
        System.out.println(notBefore);
        System.out.println(id);
        System.out.println(issuedAt);

        String nickName = (String) body.get("nickname");
        String avatar = (String) body.get("avatar");
        System.out.println(nickName);
        System.out.println(avatar);
    }


}